package com.mysoft.gfyx.workbench.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.gfyx.workbench.service.MainAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

@Service
public class MainAppServiceImp implements MainAppService {

    @Value("${main-app.app-code}")
    private String appCode;

    @Value("${main-app.host}")
    private String host;

    @Value("${main-app.iss}")
    private String iss;

    @Value("${main-app.secret}")
    private String secret;


    @Autowired
    private ContextManager contextManager;

    @Override
    public String getLoginUrl(String pageUri) throws UnsupportedEncodingException {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 30 * 60 * 1000;//有效时间5分钟
        Date expTime = new Date(currentTime);
        String gfyxSaasTenantCode = contextManager.fetchContextInfo().getTenantCode();
        String mobilePhone = contextManager.fetchContextInfo().getUserContext().getUserCode();
        String appCode = this.appCode;
        String secret = this.secret;
        String iss = this.iss;

        String token = JWT.create()
                .withClaim("tenant_code", gfyxSaasTenantCode)
                .withClaim("account", mobilePhone)
                .withClaim("app_name", appCode)
                .withIssuedAt(start)
                .withExpiresAt(expTime)
                .withIssuer(iss)
                .sign(Algorithm.HMAC256(secret));

        return this.host + "/v1/base/login/sso?access_token=" + token + "&page_uri=" + URLEncoder.encode(pageUri,  "UTF-8") +"&redirect=1";
    }
}
